<template>
	<view class="viewBg">
		<view class="uni-list" v-if="selectAction !== null">
			<view class="uni-list-cell">
				<view class="uni-list-cell-navigate uni-navigate-right" @click="showPicker">
					<text class="cell-text">{{selectAction.name}}</text>
					<text class="cell-detail">{{selectedLabel}}</text>
				</view>
			</view>
		</view>
		
		<!-- <view class="title">描述内容</view> -->
		<!-- 问题 -->
		<textarea class="uni-textarea" :placeholder="textAction.name" :value="textTitle" @focus="hiddenText" @blur="bindInputBlur" v-if="textAction !== null" :disabled="eventFlowId !== null"/>
		<view class="lineH1"></view>
		<!-- 详细描述 -->
		<view class="uni-textarea">
			<textarea  :placeholder="areaTextAction.name" :value="areaText" @blur="bindTextAreaBlur" v-if="areaTextAction !== null" :disabled="eventFlowId !== null"/>
		</view>
		<!-- 上传图片 -->
		<view class="feedback-body feedback-uploader" v-if="imageAction !== null && eventFlowId === null">
		    <view class="uni-uploader">
		        <view class="uni-uploader-head">
		            <view class="uni-uploader-title">点击上传图片</view>
		            <view class="uni-uploader-info">{{imageList.length}}/6</view>
		        </view>
		        <view class="uni-uploader-body">
		            <view class="uni-uploader__files">
		                <block v-for="(image,index) in imageList" :key="index">
		                    <view class="uni-uploader__file" style="position: relative;">
		                        <image class="uni-uploader__img" :src="image" @tap="previewImage"></image>
		                        <view class="close-view" @click="close(index)">x</view>
		                    </view>
		                </block>
		                <view class="uni-uploader__input-box" v-show="imageList.length < 6">
		                	<view class="uni-uploader__input" @tap="chooseImg"></view>
		                </view>
		            </view>
		        </view>
		    </view>
		</view>
		<view class="imageBg"  v-if="eventFlowId !== null && imageAction !== null">
			<view class="" v-for="(item,index) in imageList" :key="index">
				<image class="image" :src="item" mode="aspectFill" @click="previewImage(index)"></image>
			</view>
		</view>
		<view class="lineH1"></view>
		<view class="" v-if="videoAction !== null">
			<view class="button-sp-area" v-if="videoPath === null && eventFlowId===null">
				<button  type="default" plain="true" @click="chooseVideo">上传视频</button>
			</view>
			<view class="uni-icon-videocam" v-if="videoPath !== null && showPlayer" >
				<video :src="videoPath" controls  :show-center-play-btn="true" ></video>
			</view>
			
		</view>
		
		
		<button type="primary" @tap="saveAction" :disabled="buttonDisable" v-if="eventFlowId === null && Lhidden">保存</button>
		
		<mpvue-picker :themeColor="'#007AFF'" ref="mpvuePicker" :mode="selector" :deepLength="1" :pickerValueDefault="[0]"
		 @onConfirm="onConfirm" @onCancel="onCancel" :pickerValueArray="pickerValueArray"></mpvue-picker>
	</view>
</template>

<script>
		var lisenter;
	import mpvuePicker from "@/components/mpvue-picker/mpvuePicker.vue"
	
	export default {
		components:{mpvuePicker},
		
		data() {
			return {
				imageList: [],
				action:'',
				selectedLabel:"请选择",
				selectedValue:0,
				pickerValueArray:[],
				
				selectAction:null,
				textAction:null,
				areaTextAction:null,
				imageAction:null,
				videoAction:null,
				showPlayer:true,
				videoPath:null,
				textTitle:'',
				areaText:'',
				
				eventId:'',
				flowId:'',
				eventFlowId:null,//流转详情id
				uploadFileHeader:{},
				
				uploadingImage:false,
				uploadingVideo:false,
				
				reportListener:null,
                buttonDisable:false,
                Lhidden:true
			};
		},
		onLoad(event) {
			if(event.eventFlowId){
				console.log(event.eventFlowId +':流转id');
				this.eventFlowId =event.eventFlowId;
				this.getFlowDetail(event.eventFlowId);
                uni.setNavigationBarTitle({
                    title:'详情内容'
                })
			}else{
				console.log('表单'+decodeURIComponent( event.action));
				 this.action = JSON.parse(decodeURIComponent(event.action));
				 uni.setNavigationBarTitle({
				 	title:this.action.name
				 })
				 this.eventId = event.eventId;
				 this.flowId = event.flowId;
				 console.log('事件：'+this.eventId + '流转'+ this.flowId);
				 this.createForm();
				 
				 
				 var that = this;
				 uni.getStorage({
				 	key: "accessToken",
				 	success: function(res) {
				 		that.uploadFileHeader = { scpid:"bearer." + res.data};
				 
				 	},
				 	fail: function(error) {
				 		// console.log("main获取失败");
				 
				 	}
				 })
			}
			
			 
		},
		methods:{
            //按钮设置不可以点击状态
            buttonFun(){
                this.buttonDisable = !this.buttonDisable
            },
			createForm(){
					console.log('创建表单：'+this.action.form.length);
					var form = this.action.form;
					var images=null;
					for(var i = 0;i<form.length;i++){
						var item = form[i];
						console.log('单个'+JSON.stringify(item)+'index'+i);
						if(item.type === 'select'){
							this.selectAction = item;
							if(item.value){
								this.selectedLabel = item.value;
							}
						}
						if(item.type === 'text'){
							this.textAction = item;
							if(item.value){
								this.textTitle = item.value;
							}
						}
						if(item.type === 'textarea'){
							this.areaTextAction = item;
							if(item.value){
								this.areaText = item.value;
							}
						}
						if(item.type === 'img'){
							this.imageAction = item;
							if(item.value){
								images = item.value.split(',');								
							}
						}
						if(item.type === 'video'){
							this.videoAction = item;
							if(item.value){
								this.videoPath = 'http://image.tripln.top/gridfile'+ item.value;
							}
						}
					}
					if(images !== null){
						for(var i = 0;i<images.length;i++){
							this.imageList.push('http://image.tripln.top/gridfile'+images[i]);
						}
					}
					console.log('图片'+this.videoPath);
			},
			getFlowDetail(id){
				var that = this;
				this.$http.get('ac/xagrid/appEventServiceImpl/getFlowDetails',{id:id}).then((res)=>{
					that.action = res.data;
					console.log('获取数据'+JSON.stringify(that.action));
					that.createForm();
				
					
				})
			},
			showPicker(){
				if(this.eventFlowId !== null){
					return;
				}
				if(this.pickerValueArray.length == 0){
					this.$http.get(this.selectAction.select_list,{}).then((res)=>{
						this.pickerValueArray = res.data;
						this.$refs.mpvuePicker.show();
					});
				}else{
					this.$refs.mpvuePicker.show();
				}
				this.showPlayer = false;
				
			},
					
			onConfirm(e){
				this.selectedLabel = e.label;
				this.selectedValue = e.value;
				this.showPlayer = true;
			},
			onCancel(){
					this.showPlayer = true;
			},
			previewImage(index) { //预览图片
			    uni.previewImage({
					current:this.imageList[index],
			        urls: this.imageList
			    });
			},
			close(e){
			    this.imageList.splice(e,1);
			},
			bindInputBlur(e){
                this.Lhidden = true
				this.textTitle = e.detail.value;
			},
            hiddenText:function(){
                this.Lhidden = false
            },
			bindTextAreaBlur(e){
				this.areaText = e.detail.value;
			},
			chooseImg() { //选择图片
			    uni.chooseImage({
			        sourceType: ["camera", "album"],
			        sizeType: "compressed",
			        count: 6 - this.imageList.length,
			        success: (res) => {
			            this.imageList = this.imageList.concat(res.tempFilePaths);
			        }
			    })
			},
			//选择视频
			chooseVideo(){
				var self = this;
				uni.chooseVideo({
					sourceType:['camera','album'],
					success:function (res) {
						self.videoPath = res.tempFilePath;
					}
				})
			},
			saveAction(){
                this.buttonFun()
				var that = this;
				var params = new Object;
				params.eventId = this.eventId;
				params.flowId = this.flowId;
				params.action = this.action;
				
				var form = params.action.form;
				for(var i = 0;i<form.length;i++){
					var item = form[i];
					if(item.type === 'select'){
						if(this.selectedValue === 0){
							uni.showToast({
								title:'请选择'+item.name,
                                icon:'none'
							})
                            this.buttonFun()
							return;
						}
						item.value = String(this.selectedValue);
					}
					if(item.type === 'text'){
						console.log('文字信息')
						if(this.textTitle.length === 0){
							uni.showToast({
								title:'请输入'+item.name,
								icon:'none'
							})
                            this.buttonFun()
							return false;
						}
						item.value = this.textTitle;
					}
					if(item.type === 'textarea'){
						item.value = this.areaText;
					}
					if(item.type === 'img'){
						if(this.imageList.length >0){
							console.log('上传图片开始');
							this.uploadingImage = true;
							this.uploadImages(item);
						}
						
					}
					if(item.type === 'video'){
						if(this.videoPath !== null){
							this.uploadingVideo = true;
							this.uploadVideo(item);
						}
					}
				}
				// lisenter = setInterval(this.reportEvent,1000);
				uni.showLoading({
					title:'正在保存...'
				})
				setTimeout(function() {that.reportEvent(params)} ,1000);
				// console.log('请求参数：'+JSON.stringify(this.action));
				
			},
			//上传图片
			uploadImages(item){
				
				var that = this;
				var images = new Array();
				for(var i = 0;i<that.imageList.length;i++){
					images.push({name:'images-'+ String(i),uri:that.imageList[i]});
				}
				console.log("图片"+images + 'header'+ that.uploadFileHeader);
				uni.uploadFile({
					url: 'http://grid.tripln.top/api/xagrid/upload',
					files:images,
					fileType: 'image',
					header:that.uploadFileHeader,
					success: (res) => {
						// _contentResult = JSON.parse(res.data); //转义字符 得到结果集
						var imagePaths = new Array();
						var succData = JSON.parse(res.data);
						for (var i = 0;i<succData.data.length;i++){
							imagePaths.push(succData.data[i].path);
						}
						
						item.value = imagePaths.join(',');
						that.uploadingImage = false;
						console.log('上传图片成功后');
// 						if(that.videoPath !== null){
// 							that.uploadVideo(params);
// 						}else{
// 							that.reportEvent(params);
// 						}
						
					},
					fail: (err) => {
						console.log('uploadImage fail', err);
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						});
					}
				});
			},
			uploadVideo(item){
				var that = this;
				uni.uploadFile({
					url:'http://grid.tripln.top/api/xagrid/upload',
					fileType:'video',
					filePath:that.videoPath,
					header:that.uploadFileHeader,
					name:'data',
					success:(res)=>{
						console.log('上传视频成功'+res.data);
						var succData = JSON.parse(res.data);
						item.value = succData.data[0].path;
						that.uploadingVideo = false;
						// that.reportEvent(params);
					}
				})
			},
			reportEvent(params){
				var that = this;
				if(!this.uploadingImage && !this.uploadingVideo){
					console.log('可以保存了' +JSON.stringify(params));
					// clearInterval();
					uni.hideLoading();
					this.$http.post('ac/xagrid/appEventServiceImpl/saveEventFlow',params).then((res)=>{
						if(res.errcode === '0'){
							uni.showToast({
								title:'提交成功',
								duration:1500
							})
							setTimeout(function(){
                              that.buttonFun()
								uni.navigateBack({
								delta:2,
								})
							},1500);
						}else{
                          this.buttonFun()
							uni.showModal({
								title:'提示',
								content:res.errmsg,
								showCancel:false
							})
						}
					})
				}else{
					console.log('再等一会');
					setTimeout(function() {that.reportEvent(params)},1000);
				}
				
			}
		}
	}
</script>

<style>
.viewBg{
		width: 100%;
		height: 100%;
		
		/* background-color: #0FAEFF; */
	}
	.cell-detail{
		margin-right: 20upx;
	}
	.uni-list-cell-navigate{
		justify-content: space-between;
	}
	.title{
		padding: 20upx;
		background-color:#F7F7F7;
		color: #007AFF;
	}
	.lineH1{
		
		height: 2upx;
		width: 100%;
		/* margin-left: 10upx; */
		background-color: #F7F7F7;
	}
		.close-view{
	    text-align: center;line-height:14px;height: 16px;width: 16px;border-radius: 50%;background: #FF5053;color: #FFFFFF;position: absolute;top: -6px;right: -4px;font-size: 12px;
	}
	.button-sp-area{
		width: 40%;
	
	}
	.imageBg {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: row;
		/* margin: default; */
		flex-wrap: wrap;
		margin: 20upx;
	}
	
	.image {
		width: 150upx;
		height: 150upx;
		margin: 10upx;
	}
	button {
		/* margin-top: 30upx; */
		/* margin-bottom: 30upx; */
		margin: 30upx;
	}
	.uni-textarea{
		padding: 7px 0;
		width: 94%;
		margin-left: 3%;
	}
</style>
